# coding=utf-8
from flask import Flask
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger


class DispatcherScheduler(BackgroundScheduler):
    # 调度计划定时任务
    def __init__(self, app=None):
        super().__init__()
        if app is not None:
            self.init_app(app=app)

    def init_app(self, app: Flask):
        super().start()
        # 每次在拉起Flask服务后，第一个请求处理前执行
        app.before_first_request(self.run_all_scheduler)

    def run_all_scheduler(self):
        # 拉起所有执行计划
        from app.cores.dispatcher import apscheduler_async_project_run
        from app.models import Scheduler
        from flask import current_app, request, session

        schedulers = Scheduler.query.all()
        for scheduler in schedulers:
            if scheduler.enable:
                job_id = 'project-' + str(scheduler.element_id)
                super().add_job(func=apscheduler_async_project_run,
                                id=job_id,
                                trigger=CronTrigger.from_crontab(scheduler.cron),
                                kwargs=dict(
                                    project_id=scheduler.element_id,
                                    app=current_app._get_current_object(),
                                ),)
